package com.qs.rocketmq.right.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.qs.rocketmq.right.dto.CouponDTO;
import com.qs.rocketmq.right.entity.Coupon;
import com.qs.rocketmq.right.entity.Transaction;
import com.qs.rocketmq.right.mapper.RightMapper;
import com.qs.rocketmq.right.service.RightService;
import com.qs.rocketmq.right.service.TransactionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigInteger;
import java.util.Date;

@Slf4j
@Service
public class RightServiceImpl implements RightService {

    @Autowired
    private RightMapper rightMapper;

    @Autowired
    private TransactionService transactionService;

    @Override
    public CouponDTO getById(BigInteger couponId) {
        Coupon coupon = rightMapper.selectById(couponId);
        CouponDTO couponDTO = null;
        if (coupon != null) {
            couponDTO = new CouponDTO();
            BeanUtil.copyProperties(coupon, couponDTO);
        }

        return couponDTO;
    }

    @Transactional
    @Override
    public void useCoupon(String couponId, String transactionId) {
        Coupon coupon = rightMapper.selectById(couponId);
        if (coupon == null) {
            log.error("券不存在，couponId={}", couponId);
            throw new RuntimeException("券不存在");
        }

        // 消费端幂等判断
        if (transactionService.checkTransactionStatus(transactionId)) {
            log.info("当前消息已经消费，transactionId={}", transactionId);
            throw new RuntimeException("当前消息已经消费");
        }

        // 插入事务记录
        Transaction transaction = new Transaction();
        transaction.setTransactionId(transactionId);
        transaction.setCreateTime(new Date());
        transactionService.save(transaction);

        // 更新券
        coupon.setCount(coupon.getCount() - 1);
        rightMapper.updateById(coupon);
    }
}
